package cn.bearspark.article.provider.dao.buffer;

import cn.bearspark.article.provider.dao.key.ArticleBufferKeyBuilder;
import cn.bearspark.article.provider.dao.mapper.ArticleCategoryMapper;
import cn.bearspark.framework.redis.starter.buffer.list.RedisBaseListBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 专栏分类 id 的 list 数据结构的缓存器
 *
 * @author f
 */
@Component
public class ArticleCategoryIdListBuffer extends RedisBaseListBuffer<Long> {

    /**
     * 专栏的分类数量必定小于等于 3
     */
    private static final int IMG_MAX_SIZE = 3;

    private final ArticleCategoryMapper articleCategoryMapper;
    private final ArticleBufferKeyBuilder articleBufferKeyBuilder;

    public ArticleCategoryIdListBuffer(RedisTemplate<String, Object> redisTemplate,
                                       ArticleCategoryMapper articleCategoryMapper,
                                       ArticleBufferKeyBuilder articleBufferKeyBuilder) {
        super(redisTemplate);

        this.articleCategoryMapper = articleCategoryMapper;
        this.articleBufferKeyBuilder = articleBufferKeyBuilder;
    }

    /**
     * 获取指定专栏的分类 id
     *
     * @param articleId 待获取专栏分类 id 集合的专栏 id
     * @return 指定专栏的分类 id 集合
     */
    public List<Long> listCategoryId(long articleId) {
        return super.range(
                articleBufferKeyBuilder.buildCategoryIdListKey(articleId), 0, IMG_MAX_SIZE,
                () -> articleCategoryMapper.listCategoryId(articleId)
        );
    }

    /**
     * 清理指定专栏的分类 id 集合的缓存
     *
     * @param articleId 指定的专栏 id
     */
    public void clean(long articleId) {
        super.clean(articleBufferKeyBuilder.buildCategoryIdListKey(articleId));
    }
}
